﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Runtime.InteropServices;
using System.Windows.Input;

namespace StudioEditorTest.CodeEditor
{
	public static class Extensions
	{
		public static double GetWidth(this GridViewColumnCollection collection)
		{
			double result = 0;
			for (int i = 0; i < collection.Count; i++)
				result += collection[i].Width;
			return result;
		}
	

		[DllImport("User32.dll")]
		public static extern int MapVirtualKey(int virtualCode, MapType mapType);

		[DllImport("user32.dll")]
		public static extern int GetKeyboardState(byte[] lpKeyState);

		[DllImport("user32.dll")]
		public static extern int ToUnicode(int virtualCode, int scanCode, byte[] lpKeyState,byte[] result, int cchBuff, int flags);

		public static string GetChar(this KeyEventArgs e)
		{
			int virtualCode = KeyInterop.VirtualKeyFromKey(e.Key);
			byte[] bCharData = new byte[256];
			int keyboardState = GetKeyboardState(bCharData);
			int scanCode = MapVirtualKey(virtualCode, MapType.MAPVK_VK_TO_VSC);
			
			byte[] binaryResult = new byte[2];
			int transRes = ToUnicode(virtualCode, scanCode, bCharData, binaryResult, 2, 0);
			string result = null;
			if(transRes == 1) result = Encoding.Unicode.GetString(binaryResult);
			return result;
		}
		
		/// <summary>The set of valid MapTypes used in MapVirtualKey
		/// </summary>
		/// <remarks></remarks>
		public enum MapType : uint
		{
			/// <summary>uCode is a virtual-key code and is translated into a scan code.
			/// If it is a virtual-key code that does not distinguish between left- and
			/// right-hand keys, the left-hand scan code is returned.
			/// If there is no translation, the function returns 0.
			/// </summary>
			/// <remarks></remarks>
			MAPVK_VK_TO_VSC = 0x0,

			/// <summary>uCode is a scan code and is translated into a virtual-key code that
			/// does not distinguish between left- and right-hand keys. If there is no
			/// translation, the function returns 0.
			/// </summary>
			/// <remarks></remarks>
			MAPVK_VSC_TO_VK = 0x1,

			/// <summary>uCode is a virtual-key code and is translated into an unshifted
			/// character value in the low-order word of the return value. Dead keys (diacritics)
			/// are indicated by setting the top bit of the return value. If there is no
			/// translation, the function returns 0.
			/// </summary>
			/// <remarks></remarks>
			MAPVK_VK_TO_CHAR = 0x2,

			/// <summary>Windows NT/2000/XP: uCode is a scan code and is translated into a
			/// virtual-key code that distinguishes between left- and right-hand keys. If
			/// there is no translation, the function returns 0.
			/// </summary>
			/// <remarks></remarks>
			MAPVK_VSC_TO_VK_EX = 0x3,

			/// <summary>Not currently documented
			/// </summary>
			/// <remarks></remarks>
			MAPVK_VK_TO_VSC_EX = 0x4,
		}
	}
}
